/**
 * Copyright (c) 2014 zhenrongbao.com, Inc. All Rights Reserved
 * @author: jiangshuguang
 * @Date  : 14-12-1
 * @Time  : 上午11:55
 * @brief :
 */
(function () {
    var Dialog = require('common:widget/ui/dialog/dialog.js').Dialog,
        check = require('user:widget/ui/check/check.js').check,
        $page = $('.page-buydemand'),
        dialog = new Dialog(),
        data = P.data('data');

    $page.find('.use_coupon').bind('click', function () {
        calculateAmount();
        $('.coupon_info').show();
    });

    calculateAmount = function () {
        var buyAmount = $page.find('.money-input .amount').val();
        if(buyAmount == '') {
            buyAmount = 0;
        }
        var couponAmount = 0;
        if ($('.use_coupon').attr('checked') == 'checked') {
            $('.use_coupon').attr('data') ? couponAmount = $('.use_coupon').attr('data') : couponAmount = 0;
            P.data('coupon_type',1);
        }
        var buyValue = (parseFloat(buyAmount) * 1000 - parseFloat(couponAmount) * 1000) / 1000;
        if(buyValue < 0) {
            buyValue = 0;
        }
        $('.buy_confirm .value').text('￥' + buyValue);
        P.data('buyValue',buyValue);
    };


    $page.find('.money-input').on('input keyup',function () {
        calculateAmount();
        $('.buy_confirm').addClass('active');
    });


    $page.find('.btn-buy').click(function () {
        if ($(this).hasClass('btn-main')) {
            var originalAmount = $.trim($page.find('.amount').val()),
                amount = P.data('buyValue'),
                flag = true;

            if (!check.amount(originalAmount)) {
                return;
            }

            if (parseFloat(amount) > data['amount']) {
                dialog.show('您的购买金额大于您的账户可用余额');
                return;
            }

            if (parseFloat(originalAmount) > data['available_amount']) {
                dialog.show('您的购买金额大于您的剩余可购买额度');
                return;
            }

            $(this).addClass('btn-disable').removeClass('btn-main');
            $.post('/user/purchasing', {
                amount: originalAmount,
                coupon_type: P.data('coupon_type'),
                pid: 1
            }, function (ret, status) {
                if (ret.error_no == 0) {
                    location.href = "/user/buyingdemand?pid=1&trade_id=" + ret.data
                } else {
                    dialog.show(ret.error_message);
                }
            }, 'json');
        }
    });
})();